<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="出库状态" prop="ckZt">
            <el-select v-model="queryParams.ckZt" placeholder="请选择出库状态" clearable>
              <el-option
                v-for="dict in dict.type.wzgl_ckzt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库方式" prop="ckFs">
            <el-select v-model="queryParams.ckFs" placeholder="请选择出库方式" clearable>
              <el-option
                v-for="dict in dict.type.wzgl_ckfs"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工区" prop="gq">
            <el-input
              v-model="queryParams.gq"
              placeholder="请输入工区"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库日期">
            <el-date-picker
              v-model="daterangeCkTime"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="出库人" prop="ckName">
            <el-input
              v-model="queryParams.ckName"
              placeholder="请输入出库人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物资名称" prop="wzName">
            <el-input
              v-model="queryParams.wzName"
              placeholder="请输入物资名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wzgl:wzck:add']"
        >新增出库单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['wzgl:wzck:edit']"
        >修改出库单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="!selectedRow || (selectedRow.ckZt != '待出库')"
          @click="handleDelete"
          v-hasPermi="['wzgl:wzck:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wzgl:wzck:export']"
        >导出Excel
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          icon="el-icon-upload2"-->
      <!--          size="mini"-->
      <!--          @click="handleImport"-->
      <!--          v-hasPermi="['wzgl:wzck:import']"-->
      <!--        >导入</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table height="300" class="fixedTableTwo" @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="wzckList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="出库状态" align="center" prop="ckZt" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wzgl_ckzt" :value="scope.row.ckZt"/>
        </template>
      </el-table-column>
      <el-table-column label="出库日期" align="center" prop="ckTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ckTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出库方式" align="center" prop="ckFs">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wzgl_ckfs" :value="scope.row.ckFs"/>
        </template>
      </el-table-column>
      <el-table-column label="工区" align="center" prop="gq"/>
      <el-table-column label="出库人" align="center" prop="ckName"/>
      <el-table-column label="所属部门" align="center" prop="deptName"/>
      <el-table-column label="出库详情" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleCkXqClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-link style="color: #44d744; font-weight: 600" type="danger" disabled v-if="scope.row.ckZt == '出库完成'">
            {{ '已出库完成' }}
          </el-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="qdCk(scope.row)"
            v-if="scope.row.ckZt == '待出库'"
          >确定出库
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.ckZt == '待出库'"
            v-hasPermi="['wzgl:wzck:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.ckZt == '待出库'"
            v-hasPermi="['wzgl:wzck:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 导入对话框 -->
    <vxe-modal :title="upload.title" v-model="upload.open" width="400px" showFooter show-zoom resize>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 添加或修改物资出库对话框 -->
    <vxe-modal :title="title" v-model="open" width="79%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">出库基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="出库方式" prop="ckFs">
                <el-select :disabled="xg" v-model="form.ckFs" placeholder="请选择出库方式">
                  <el-option
                    v-for="dict in dict.type.wzgl_ckfs"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :rules="[{ required: true, message: '请选择工区', trigger: 'blur' }]"
                            v-if="form.ckFs == '调拨出库'" label="工区" prop="gq">
                <!--                <el-input v-model="form.gq" placeholder="请输入工区"/>-->
                <el-select filterable v-model="form.gq" placeholder="请选择工区" style="width: 100%">
                  <el-option
                    v-for="item in gqList"
                    :key="item.gqglId"
                    :label="item.gqName"
                    :value="item.gqName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出库日期" prop="ckTime">
                <el-date-picker clearable style="width: 100%;"
                                v-model="form.ckTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择出库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出库人" prop="ckName">
                <el-input v-model="form.ckName" placeholder="请输入出库人"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">出库明细信息</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWzckCkmx">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWzckCkmx">删除</el-button>
            </el-col>
          </el-row>
          <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    height="45vh" :data="wzckCkmxList" :row-class-name="rowWzckCkmxIndex"
                    @selection-change="handleWzckCkmxSelectionChange" ref="wzckCkmx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column align="center" label="序号" type="index" width="50"/>
            <!--            <el-table-column align="center" label="物资信息ID" prop="wzxxId"/>-->
            <el-table-column show-overflow-tooltip align="center" label="物资名称" prop="wzName">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleButtonClick(scope.row)"
                >
                  <el-link style="font-weight: 600" type="primary">{{ scope.row.wzName }}</el-link>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" label="物资单位" prop="wzDw"/>
            <el-table-column show-overflow-tooltip align="center" label="仓库名称" prop="ckName"/>
            <el-table-column show-overflow-tooltip align="center" label="货架名称" prop="hjName"/>
            <el-table-column show-overflow-tooltip align="center" label="分层名称" prop="fcName"/>
            <el-table-column show-overflow-tooltip align="center" label="物资分类" prop="wzFl"/>
            <el-table-column show-overflow-tooltip align="center" label="物资规格" prop="wzGg"/>
            <el-table-column show-overflow-tooltip align="center" label="物资专业" prop="wzZy"/>
            <el-table-column show-overflow-tooltip align="center" label="领用人" prop="lyName">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lyName" placeholder="请输入"/>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" label="单价(元)" prop="dj"/>
            <el-table-column show-overflow-tooltip align="center" label="出库数量" prop="ckSl">
              <template slot-scope="scope">
                <el-input type="number" @change="calculateHJJE(scope.$index)" v-model="scope.row.ckSl"
                          placeholder="请输入"/>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" label="合计金额(元)" prop="hjJe">
              <template slot-scope="scope">
                {{ calculateTotal(scope.row) || '' }}
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" label="备注" prop="bz">
              <template slot-scope="scope">
                <el-input v-model="scope.row.bz" placeholder="请输入"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button v-if="form.ckFs == '调拨出库'" type="primary" @click="submitForm">确 定</el-button>
        <el-button v-if="form.ckFs == '报废出库'" type="primary" @click="bfCk">报 废 出 库</el-button>
        <el-button v-if="form.ckFs == '个人领用出库'" type="primary" @click="grLyCk">个 人 领 用 出 库</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 物资多选 -->
    <WzDuoX ref="wzDuoX"/>

    <!-- 物资详情 -->
    <WzXq ref="wzXq"/>

    <!-- 物资出库详情 -->
    <WzCkXq ref="wzCkXq"/>
  </div>
</template>

<script>
import {addWzck, delWzck, getWzck, insertBfCk, insertGrLyCk, listWzck, updateQdck, updateWzck} from "@/api/wzgl/wzck";
import {getToken} from "@/utils/auth";
import WzDuoX from "@/views/components/WzDuoX/index.vue";
import {selectByQxGq} from "@/api/wzgl/gqgl";
import WzXq from "@/views/wzgl/wzxx/components/WzXq.vue";
import {getWzxx, updateWzxx} from "@/api/wzgl/wzxx";
import WzCkXq from "@/views/wzgl/wzck/components/WzCkXq.vue";

export default {
  name: "Wzck",
  components: {WzCkXq, WzXq, WzDuoX},
  dicts: ['wzgl_ckfs', 'wzgl_ckzt'],
  provide() {
    return {
      updateWzLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.wzckCkmxList.some(existingItem => existingItem.wzxxId === item.wzxxId);
          if (!exists) {
            this.wzckCkmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      xg: false,
      gqList: [], //后端获取到的工区列表(数据权限校验)
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWzckCkmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资出库表格数据
      wzckList: [],
      // 出库明细表格数据
      wzckCkmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 合计金额时间范围
      daterangeCkTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ckZt: null,
        ckFs: null,
        gq: null,
        ckTime: null,
        ckName: null,
        userId: null,
        deptId: null,
        wzName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ckFs: [{required: true, message: "出库方式不能为空", trigger: "change"}],
        ckTime: [{required: true, message: "出库日期不能为空", trigger: "blur"}],
        ckName: [{required: true, message: "出库人不能为空", trigger: "blur"}],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wzgl/wzck/importData"
      }
    };
  },
  created() {
    this.getList();

    selectByQxGq().then(res => {
      this.gqList = res.data
    })
  },
  methods: {
    //查询物资出库详情
    handleCkXqClick(row) {
      this.$refs.wzCkXq.handleOpen(row)
    },
    //确定出库
    qdCk(row) {
      this.$confirm('是否确认出库? 入库完成后将无法再次修改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在完成出库中，请稍后...");
        this.form.ckZt = '出库完成'
        this.form.wzckId = row.wzckId
        this.form.gq = row.gq
        this.form.wzckCkmxList = this.wzckCkmxList
        updateQdck(this.form).then(res => {
          this.$modal.closeLoading();
          this.getList();
          this.$modal.msgSuccess("出库完成!");
          this.$modal.closeLoading();
        }).catch(error => {
          this.$modal.closeLoading();
        })
        // this.qdCks(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //出库逻辑
    // qdCks(row) {
    //   const wzckId = row.wzckId
    //   const gq = row.gq
    //
    //   getWzck(wzckId).then(res => {
    //     const wzckCkmxList = res.data.wzckCkmxList;
    //     this.wzckCkmxList = wzckCkmxList;
    //
    //     // 创建一个Promise数组，用于存储每个物资的检查Promise
    //     const checkPromises = [];

        // 循环物资列表，为每个物资创建一个检查Promise
        // for (let i = 0; i < wzckCkmxList.length; i++) {
        //   let item = wzckCkmxList[i];
        //   let ckSl = item.ckSl; //出库数量
        //
        //   checkPromises.push(
        //     getWzxx(item.wzxxId).then(res => {
        //       let wzKc = res.data.kc; //物资库存
        //       if (ckSl > wzKc) {
        //         // 返回一个错误，表示该物资的检查未通过
        //         return Promise.reject(`出库明细中: 物资名称: ${item.wzName}`);
        //       } else {
        //         // 返回null或任何其他值，表示检查通过
        //         return null;
        //       }
        //     })
        //   );
        // }

        // // 使用Promise.all等待所有检查完成
        // Promise.all(checkPromises)
        //   .then(() => {
        //     // 所有检查都通过了
        //     console.log('所有物资的出库数量均小于等于库存');
        //     for (let i = 0; i < wzckCkmxList.length; i++) {
        //       let item = wzckCkmxList[i]
        //       let ckSl = item.ckSl //该物资现在要出库的数量
        //
        //       getWzxx(item.wzxxId).then(res => {
        //         let wzKc = res.data.kc //该物资入库之前的库存
        //         //初始化物资信息所需的表单内容, 将获取到的物资ID放置, 将原本库存减去出库数量
        //         this.wzForm = {
        //           wzxxId: item.wzxxId,
        //           wzName: null,
        //           wzDw: null,
        //           ssCk: null,
        //           ssHj: null,
        //           ssFc: null,
        //           wzFl: null,
        //           aqKc: null,
        //           wzGg: null,
        //           wzZy: null,
        //           dj: null,
        //           wzBz: null,
        //           createBy: null,
        //           createTime: null,
        //           updateBy: null,
        //           updateTime: null,
        //           userId: null,
        //           deptId: null,
        //           kc: Number(wzKc) - Number(ckSl),
        //           ckGlZt: null,
        //           ghPlZb: null
        //         };
        //         //更新物资信息中的库存
        //         updateWzxx(this.wzForm).then(res => {
        //         });
        //       });
        //     }
        //     this.form.ckZt = '出库完成'
        //     this.form.wzckId = wzckId
        //     this.form.gq = gq
        //     this.form.wzckCkmxList = this.wzckCkmxList
        //     updateQdck(this.form).then(res => {
        //       this.$modal.closeLoading();
        //       this.getList();
        //       this.$modal.msgSuccess("出库完成!");
        //       this.$modal.closeLoading();
        //     })
          // })
          // .catch(error => {
          //   // 至少有一个物资的检查未通过
          //   // this.$modal.msgError(`出库明细中存在出库数量大于库存的现象!  ${error}, 请检查!`);
          //   this.$modal.alertError(`出库明细中存在出库数量大于库存的现象!${error}, 请检查!`);
          //   this.$modal.closeLoading();
          // });
      // });
    // 查看物资详情信息
    handleButtonClick(row) {
      this.$refs.wzXq.handleOpen(row);
    },
    //将合计金额绑定到表单项
    calculateHJJE(index) {
      const row = this.wzckCkmxList[index];
      let wzxxId = row.wzxxId
      getWzxx(wzxxId).then(res => {
        if (row.ckSl > res.data.kc) {
          this.$modal.alertError("出库数量大于库存, 该物资当前的库存为:" + res.data.kc);
          // this.$modal.msgError("出库数量大于库存, 该物资当前的库存为:" + res.data.kc);
          row.ckSl = null
        } else {
          row.hjJe = row.dj * row.ckSl;
        }
      })
    },
    // 计算合计金额的方法 (只是实时计算并显示, 未绑定)
    calculateTotal(row) {
      if (row.dj && row.ckSl) {
        return parseFloat(row.dj) * parseFloat(row.ckSl);
      }
      return ''; // 当入库数量为空时，返回空字符串
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询物资出库列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCkTime && '' != this.daterangeCkTime) {
        this.queryParams.params["beginCkTime"] = this.daterangeCkTime[0];
        this.queryParams.params["endCkTime"] = this.daterangeCkTime[1];
      }
      listWzck(this.queryParams).then(response => {
        this.wzckList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wzckId: null,
        ckZt: null,
        ckFs: null,
        gq: null,
        ckTime: null,
        ckName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.wzckCkmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCkTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wzckId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      this.reset();
      this.form.ckName = this.$store.state.user.name
      this.open = true;
      this.title = "添加物资出库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.xg = true
      this.reset();
      const wzckId = row.wzckId || this.ids
      getWzck(wzckId).then(response => {
        this.form = response.data;
        this.wzckCkmxList = response.data.wzckCkmxList;
        this.open = true;
        this.title = "修改物资出库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wzckCkmxList = this.wzckCkmxList;

          if (this.form.wzckCkmxList.length == 0) {
            this.$modal.msgError("物资出库明细不能为空");
            return
          }
          for (let i = 0; i < this.form.wzckCkmxList.length; i++) {
            let item = this.form.wzckCkmxList[i]
            if (item.ckSl == undefined || item.ckSl == null || item.ckSl == '') {
              this.$modal.msgError("第" + (i + 1) + "行，出库数量为空，请检查");
              return
            }
          }

          if (this.form.wzckId != null) {
            updateWzck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWzck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 报废出库按钮 */
    bfCk() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wzckCkmxList = this.wzckCkmxList;

          if (this.form.wzckCkmxList.length == 0) {
            this.$modal.msgError("物资出库明细不能为空");
            return
          }
          for (let i = 0; i < this.form.wzckCkmxList.length; i++) {
            let item = this.form.wzckCkmxList[i]
            if (item.ckSl == undefined || item.ckSl == null || item.ckSl == '') {
              this.$modal.msgError("第" + (i + 1) + "行，出库数量为空，请检查");
              return
            }
          }

          insertBfCk(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 个人领用出库按钮 */
    grLyCk() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wzckCkmxList = this.wzckCkmxList;

          if (this.form.wzckCkmxList.length == 0) {
            this.$modal.msgError("物资出库明细不能为空");
            return
          }
          for (let i = 0; i < this.form.wzckCkmxList.length; i++) {
            let item = this.form.wzckCkmxList[i]
            if (item.ckSl == undefined || item.ckSl == null || item.ckSl == '') {
              this.$modal.msgError("第" + (i + 1) + "行，出库数量为空，请检查");
              return
            }
          }

          insertGrLyCk(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wzckIds = row.wzckId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delWzck(wzckIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 出库明细序号 */
    rowWzckCkmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 出库明细添加按钮操作 */
    handleAddWzckCkmx() {
      this.$refs.wzDuoX.handleOpen(this.wzckCkmxList)
      // let obj = {};
      // obj.wzxxId = "";
      // obj.wzName = "";
      // obj.wzDw = "";
      // obj.ckName = "";
      // obj.hjName = "";
      // obj.fcName = "";
      // obj.wzFl = "";
      // obj.wzGg = "";
      // obj.wzZy = "";
      // obj.lyName = "";
      // obj.bz = "";
      // obj.dj = "";
      // obj.ckSl = "";
      // obj.hjJe = "";
      // this.wzckCkmxList.push(obj);
    },
    /** 出库明细删除按钮操作 */
    handleDeleteWzckCkmx() {
      if (this.checkedWzckCkmx.length == 0) {
        this.$modal.msgError("请先选择要删除的出库明细数据");
      } else {
        const wzckCkmxList = this.wzckCkmxList;
        const checkedWzckCkmx = this.checkedWzckCkmx;
        this.wzckCkmxList = wzckCkmxList.filter(function (item) {
          return checkedWzckCkmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWzckCkmxSelectionChange(selection) {
      this.checkedWzckCkmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wzgl/wzck/export', {
        ...this.queryParams
      }, `wzck_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('wzgl/wzck/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物资出库导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
